package cn.lingyangwl.agile.msg.push.core.sender;

import cn.lingyangwl.agile.msg.push.api.constatnts.*;
import cn.lingyangwl.agile.msg.push.api.model.content.*;
import cn.lingyangwl.agile.msg.push.core.*;
import cn.lingyangwl.agile.msg.push.core.channel.*;
import cn.lingyangwl.agile.msg.push.core.channel.client.*;
import cn.lingyangwl.framework.tool.core.*;
import cn.lingyangwl.framework.tool.core.exception.*;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author shenguangyang
 */
@Slf4j
@Service
public class EmailSender implements MsgSender {
    @Resource
    private ChannelClientManager channelClientManager;

    @Override
    public void sendMessage(PushTaskContext context) {
        AbstractEmailMsgClient msgChannelClient = (AbstractEmailMsgClient) channelClientManager.getChannelClient(context.getChannelType());
        MailProperties mailProperties = msgChannelClient.getMailProperties();
        JavaMailSenderImpl mailSender = msgChannelClient.getJavaMailSender();
        context.setChannelCode(msgChannelClient.channelCode());

        MsgParam msgParam = (MsgParam) context.getMsgParam();

        String fromAddress = mailProperties.getUsername();
        MsgSettings msgSettings = context.getMsgSettings();
        log.debug("send msg to email, msg: {}", JSON.toJSONString(context.getMsgSettings(), JSONWriter.Feature.WriteEnumsUsingName));
        if (StringUtils.isEmpty(fromAddress)) {
            throw new BizException("尚未配置邮件");
        }

        MimeMessage message = mailSender.createMimeMessage();
        try {
            // true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            helper.setFrom(fromAddress);
            helper.setTo(msgParam.getToUser());
            helper.setSubject(context.getMsgParam().getTitle());
            helper.setText(msgSettings.getRenderContent(), true);
            mailSender.send(message);
        } catch (MessagingException | MailAuthenticationException e) {
            context.setPushStatus(MsgPushStatus.FAIL);
            context.setPushResult(e.getMessage());
            log.error("send mail to [{}] fail, error: {}", msgParam.getToUser(), e.getMessage());
            if (e instanceof MailAuthenticationException) {
                throw new BizException("邮箱授权失败-请确认账号以及授权码是否正确");
            }
        }
    }

    @Override
    public ChannelTypeEnum channelType() {
        return ChannelTypeEnum.EMAIL;
    }
}
